import { memo, useCallback, useRef } from "react";
import { PlusOutlined } from "@ant-design/icons";
import Compressor from "compressorjs";
import styles from "./index.module.scss";

interface IProps {
  value?: string;
  onChange?: any;
  size?: number;
}

function UploadImg(props: IProps) {
  const { value, onChange, size = 200 } = props;
  const uploadInputRef = useRef<HTMLInputElement>(null);

  const uploadPhoto = async (event: any) => {
    if (!event.target.files?.length) return;
    const file = event.target.files[0];
    // 压缩图片
    new Compressor(file, {
      quality: 1,
      maxWidth: size,
      maxHeight: size,
      success(result) {
        const reader = new FileReader();
        reader.readAsDataURL(result);
        reader.onload = function (e) {
          if (!e.target?.result) return;
          onChange?.(e.target.result as string);
        };
      },
    });
  };

  const openUpload = useCallback(() => {
    uploadInputRef.current?.click();
  }, []);

  return (
    <div className={styles.content}>
      <img className={styles.img} src={value} alt="" />
      <div className={styles.upload} onClick={openUpload}>
        <PlusOutlined className={styles.uploadIcon} />
        <span className={styles.uploadText}>
          {value ? "更换图片" : "上传图片"}
        </span>
      </div>
      <input
        style={{ display: "none" }}
        ref={uploadInputRef}
        type="file"
        onChange={uploadPhoto}
        accept="image/*"
      />
    </div>
  );
}

export default memo(UploadImg);
